<?php
defined('ABSPATH') or die("No script kiddies please!");
add_theme_support( 'post-thumbnails' );
add_theme_support( 'post-formats', array( 'gallery', 'video' ) );

add_filter('show_admin_bar', '__return_false');

// register menu
function ap_cate_menu() {
  register_nav_menu('category-menu',__( 'Category Menu' ));
}
add_action( 'init', 'ap_cate_menu' );

// custom filter by title
function title_like_posts_where( $where, &$wp_query ) {
	global $wpdb;
	if ( $post_title_like = $wp_query->get( 'post_title_like' ) ) {
		$where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'' . esc_sql( like_escape( $post_title_like ) ) . '%\'';
	}
	return $where;
}

/*
	Get custom posts according to multiple requirements
	$options = array(
		'limit' => 20, // number of posts to retrieve
		'level' => 1, // limit the level of post
		'orderby' => 'date|level', // order posts by
		'order' => 'DESC|ASC', // in what order
		'age' => 7, // limit ages (in day) of post
		'tags' => 'my-tam,tag-slug', // filter by tags
		'categories' => 'showbiz,cate-slug', // filter by categories
		'formats' => 'post-format-video,post-format-gallery', // filter by article type
		'exclude' => '1,2,3', // post_id to be excluded
		'before' => '<div>', // HTML to be appended before (default = "")
		'after' => '</div>' // HTML to be appended after (default="")
	)
*/
function ap_get_posts($class='block-layout',$options = array()){
	// setup default configurations
	$args = array(
		'posts_per_page' => 20,
		'post_type' => 'post',
		'post_status' => 'publish'
	);
	// if user specify limit number of post
	if(array_key_exists('limit', $options)) {
		$args = array_merge($args,array('posts_per_page'=>$options['limit']));
	}
	// if user choose only display post higher than certain level
	if(array_key_exists('level', $options)) {
		$args = array_merge($args,array(
			'meta_query' => array(
				'relation' => 'AND',
				array(
					'key' => 'level',
					'value' => $options['limit'],
					'type' => 'NUMERIC',
					'compare' => '<='
				)
			)
		));
	}
	// if user filter search by keyword in title
	if(array_key_exists('search', $options)) {
		$args = array_merge($args,array(
			's' => $options['search'],
			'exact' => false,
			'sentence' => true
		));
	}
	// if user choose to order post in certain way
	if(array_key_exists('orderby', $options)) {
		$order = 'DESC';
		if(array_key_exists('order', $options)) {
			$order = $options['order'];
		}
		if(!in_array($options['orderby'], array('date','modified','rand','comment_count'))) {
			$args = array_merge($args,array(
				'meta_key' => $options['orderby'],
				'orderby' => 'meta_value_num',
				'order' => $order
			));
		} else {
			$args = array_merge($args,array(
				'orderby' => $options['orderby'],
				'order' => $order
			));
		}
	}
	// if user choose to limit post in the last N days
	if(array_key_exists('age', $options) && $options['age']!==false) {
		$now = new DateTime(null,new DateTimeZone('Asia/Ho_Chi_Minh'));
		$now->sub(date_interval_create_from_date_string($options['age'].' days'));
		$args = array_merge($args,array(
			'date_query' => array(
				array(
					'after' => $options['age'].' days ago'
				)
			)
		));
	}
	// select by tag
	if(array_key_exists('tags', $options) && $options['tags']!==false) {
		$args = array_merge($args,array(
			'tag' => $options['tags']
		));
	}
	// select by category
	if(array_key_exists('categories', $options) && $options['categories']!==false) {
		$args = array_merge($args,array(
			'category_name' => $options['categories']
		));
	}
	// select by post type
	if(array_key_exists('formats', $options) && $options['formats']!==false) {
		$args = array_merge($args,array(
			'tax_query' => array(
				array(
					'taxonomy' => 'post_format',
					'field' => 'slug',
					'terms' => explode(',', $options['formats'])
				)
			)
		));
	}
	// exclude certain posts
	$exclude = "";
	if(array_key_exists('exclude', $options) && $options['exclude']!==false) {
		$exclude = $options['exclude'].",";
	}
	
	// var_dump($args);
	
	// get results
	$the_query = new WP_Query($args);
	if( $the_query->have_posts() ) {
		$counter = 0;
		$wrapped = false;
		while ( $the_query->have_posts() ) {
			$the_query->the_post();
			if(strpos($exclude,((string)get_the_ID().","))!==false) {
				continue;
			}
			if($counter==0 && array_key_exists('before', $options)) {
				echo $options['before'];
				$wrapped = true;
			}
			

			if(array_key_exists('featured', $options) && $options['featured']===true && $counter==0) {
				ap_render_post($class,true,$options);
			} else {
				ap_render_post($class,false,$options);
			}

			$counter++;
		}
		if($wrapped && array_key_exists('after', $options)) {
			echo $options['after'];
		}
	} else {
		// no posts found
	}
	wp_reset_query();  // Restore global post data stomped by the_post().
}

function ap_render_post($class="",$featured=false,$options=array()) {
	echo '<article class="article  '.$class.' '.get_post_format().' '.join(' ',get_post_class());
		if($featured) {
			echo " featured";
		}
		echo '">';
	if(has_post_thumbnail()) {
		echo '<p class="thumbnail" style="background-image:url('.wp_get_attachment_url(get_post_thumbnail_id($post->ID)).')">';
			echo '<a href="'.esc_url(get_permalink()).'">';
				echo get_the_post_thumbnail();
			echo '</a>';
		echo '</p>';
	}
	echo '<header>';
		echo '<h1 class="title"><a href="'.esc_url( get_permalink() ).'" rel="bookmark">'.get_the_title().'</a></h1>';
		echo '<p class="meta">';
			if(array_key_exists('level', $options) && $options['level']===true){
				echo '<span class="level">'.get_field('post-level').'</span>';
			}
			echo '<span class="category">'.ap_get_categories().'</span> | ';
			if(array_key_exists('views', $options) && $options['views']===true) {
				echo '<span class="pageview">'.(int)get_post_meta(get_the_ID(),'views',true).' xem</span> | ';
			}
			echo '<span class="datetime">'.ap_get_publish_time(array('time'=>true,'weekday'=>true)).'</span> ';
		echo '</p>';
		if(!array_key_exists('summary', $options) || $options['summary']===true) {
			echo '<p class="summary">'.ap_get_the_excerpt(250).'</p>';
		}
		if(array_key_exists('tag', $options) && $options['tag']===true) {
			echo get_the_tag_list('<p class="tags">Chủ đề: ',', ','</p>');
		}
	echo '</header>';
	echo '</article>';
}

function ap_get_categories($separator=', ') {
	$categories = get_the_category();
	$output = "";
	if($categories) {
		foreach ($categories as $category) {
			if($category->term_id != 1) {
				$output .= '<a class="cate-'.$category->term_id.'" href="'.get_category_link( $category->term_id ).'" title="'.esc_attr( sprintf( __( "Xem chuyên mục %s" ), $category->name )).'">'.$category->cat_name.'</a>'.$separator;
			}
		}
	}
	return trim($output,$separator);
}

function ap_get_category_slugs($separator=',') {
	$categories = get_the_category();
	$output = "";
	if($categories) {
		foreach ($categories as $category) {
			$output .= ($category->slug).$separator;
		}
	}
	return trim($output,$separator);
}

function ap_related_articles($post_layout="",$options = array('post_id'=>false,'category'=>false,'limit'=>5,'widget_id'=>"",'order_by'=>'date')) {
	$article_id = get_the_ID();
	if(array_key_exists('post_id',$options)) {
		$article_id = $options['post_id'];
	};
	// retrieve tags of article
	$topics = "";
	$tags = get_the_tags($article_id);
	if($tags) {
		foreach ($tags as $tag) {
			$topics .= $tag->slug.",";
		}
		$topics = preg_replace('/,$/', '', $topics);
	}
	// if user specified to limit by category as well
	$categories = false;
	if(array_key_exists('category',$options) && $options['category']===true) {
		$categories = "";
		foreach (get_the_category($article_id) as $category) {
			$categories .= $category->slug.",";
		}
		$categories = preg_replace('/,$/', '', $categories);
	}
	// now print the section
	ap_get_posts($post_layout,array(
		'limit'=>array_key_exists('limit',$options)?$options['limit']:5,
		'orderby'=>array_key_exists('order_by',$options)?$options['order_by']:'date',
		'tags'=>$topics,
		'categories'=>$categories,
		'exclude'=>(string)get_the_ID(), // exclude the current post
		'before' => '<section class="widget" id="'.$options['widget_id'].'"><header class="widget-header"><h1>Liên quan</h1></header><div class="widget-content">',
		'after' => "</div></section>"
	));

}

function ap_get_publish_time($options = array('time'=>false,'weekday'=>false)) {
	$dates = array(
		'Monday' => 'Thứ hai',
		'Tuesday' => 'Thứ ba',
		'Wednesday' => 'Thứ tư',
		'Thursday' => 'Thứ năm',
		'Friday' => 'Thứ sáu',
		'Saturday' => 'Thứ bảy',
		'Sunday' =>' Chủ nhật'
	);
	$output = "";
	if (array_key_exists('time', $options) && $options['time']===true) {
		$output .= '<span>'.get_the_time('H:i').'</span> ';
	}
	if (array_key_exists('weekday', $options) && $options['weekday']===true) {
		$output .= $dates[get_the_date(l)].', ngày ';
	}
	$output .= get_the_date("d/m/Y");
	return $output;
}

function filter_where($where = '') {
	//posts in the last 30 days
	//$where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
	//posts  30 to 60 days old
	//$where .= " AND post_date >= '" . date('Y-m-d', strtotime('-60 days')) . "'" . " AND post_date <= '" . date('Y-m-d', strtotime('-30 days')) . "'";
	//posts for March 1 to March 15, 2009
	$where .= " AND post_date >= '2009-03-01' AND post_date <= '2009-03-15'";
	return $where;
  }

/* Get the excerpt of post by max number of characters */
function the_excerpt_max_charlength($charlength) {
	$excerpt = get_the_excerpt();
	$charlength++;

	if ( mb_strlen( $excerpt ) > $charlength ) {
		$subex = mb_substr( $excerpt, 0, $charlength - 5 );
		$exwords = explode( ' ', $subex );
		$excut = - ( mb_strlen( $exwords[ count( $exwords ) - 1 ] ) );
		if ( $excut < 0 ) {
			echo mb_substr( $subex, 0, $excut );
		} else {
			echo $subex;
		}
		echo '[...]';
	} else {
		echo $excerpt;
	}
}

function app_pagination() {
	global $wp_query, $wp_rewrite;
    echo $wp_query;
	// Don't print empty markup if there's only one page.
	if ( $wp_query->max_num_pages < 2 ) {
	  
		return;
	}

	$paged        = get_query_var( 'paged' ) ? intval( get_query_var( 'paged' ) ) : 1;
	$pagenum_link = html_entity_decode( get_pagenum_link() );
	$query_args   = array();
	$url_parts    = explode( '?', $pagenum_link );

	if ( isset( $url_parts[1] ) ) {
		wp_parse_str( $url_parts[1], $query_args );
	}

	$pagenum_link = remove_query_arg( array_keys( $query_args ), $pagenum_link );
	$pagenum_link = trailingslashit( $pagenum_link ) . '%_%';

	$format  = $wp_rewrite->using_index_permalinks() && ! strpos( $pagenum_link, 'index.php' ) ? 'index.php/' : '';
	$format .= $wp_rewrite->using_permalinks() ? user_trailingslashit( $wp_rewrite->pagination_base . '/%#%', 'paged' ) : '?paged=%#%';

	// Set up paginated links.
	$links = paginate_links( array(
		'base'     => $pagenum_link,
		'format'   => $format,
		'total'    => $wp_query->max_num_pages,
		'current'  => $paged,
		'mid_size' => 1,
		'add_args' => array_map( 'urlencode', $query_args ),
		'prev_text' => __( '&larr; Mới hơn', 'twentyfourteen' ),
		'next_text' => __( 'Cũ hơn &rarr;', 'twentyfourteen' ),
	) );

	if ( $links ) :

	?>
	<p class="article-pagination">
			<?php echo $links; ?>
	</p>
	<?php
	endif;
}

function ap_get_the_excerpt($charlength) {
	$excerpt = get_the_excerpt();
	$charlength++;
	$output = "";
	if ( mb_strlen( $excerpt ) > $charlength ) {
		$subex = mb_substr( $excerpt, 0, $charlength - 5 );
		$exwords = explode( ' ', $subex );
		$excut = - ( mb_strlen( $exwords[ count( $exwords ) - 1 ] ) );
		if ( $excut < 0 ) {
			$output = mb_substr( $subex, 0, $excut );
		} else {
			$output = $subex;
		}
		$output = $output.'[...]';
	} else {
		$output = $excerpt;
	}
	return $output;
}

function ap_get_video_attachment() {
	return get_field('video-attachment',get_the_ID(),false);
}

function ap_get_author() {
	return get_field('article-author');
}

function ap_get_source() {
	return get_field('article-source');
}

function ap_get_source_link() {
	return get_field('article-source-link');
}

add_filter( 'wp_title', 'baw_hack_wp_title_for_home' );
function baw_hack_wp_title_for_home( $title )
{
  if( empty( $title ) && ( is_home() || is_front_page() ) ) {
	return __( 'Báo Rất Mới', 'theme_domain' ) . ' | ' . get_bloginfo( 'description' );
  }
  return $title;
}
?>